import 'package:dio/dio.dart';
import 'package:fsharing/core/models/business_apply.dart';
import 'package:fsharing/core/models/business_condition.dart';
import 'package:fsharing/core/models/business_level.dart';
import 'package:fsharing/core/services/api.dart';
import 'package:fsharing/core/viewmodels/view_model.dart';

class BusinessApplyModel extends ViewModel {
  final Api api;
  final BusinessCondition businessCondition;
  final Map<ProductOption, bool> _checkMap = {};
  final Map<ProductOption, int> _quantityMap = {};

  String _errorMessage;
  List<BusinessApply> _list;

  BusinessApplyModel(this.api, this.businessCondition) : super() {
    _setCheckDefault(businessCondition);
  }

  /// 设置默认
  void _setCheckDefault(BusinessCondition businessCondition) {
    for (PurchaseCondition purchaseCondition in businessCondition.purchaseConditions) {
      for (ProductOption productOption in purchaseCondition.productOptions) {
        _checkMap[productOption] = productOption.selected;
      }
    }
  }

  bool getCheckAll(BusinessCondition businessCondition) {
    for (PurchaseCondition purchaseCondition in businessCondition.purchaseConditions) {
      for (ProductOption productOption in purchaseCondition.productOptions) {
        if (!getCheckProductOption(productOption)) {
          return false;
        }
      }
    }
    return true;
  }

  void setCheckAll(BusinessCondition businessCondition, bool check) {
    for (PurchaseCondition purchaseCondition in businessCondition.purchaseConditions) {
      for (ProductOption productOption in purchaseCondition.productOptions) {
        if (productOption.canModified) {
          _checkMap[productOption] = check;
        }
      }
    }
    notifyListeners();
  }

  bool getCheckProductOption(ProductOption productOption) {
    return _checkMap[productOption] ?? false;
  }

  void setCheckProductOption(ProductOption productOption, bool check) {
    if (productOption.canModified) {
      _checkMap[productOption] = check;
      notifyListeners();
    }
  }

  int getQuantityProductOption(ProductOption productOption) {
    return _quantityMap[productOption] ?? productOption.minPurchaseAmount;
  }

  void setQuantityProductOption(ProductOption productOption, int quantity) {
    _quantityMap[productOption] = quantity;
    notifyListeners();
  }

  /// 获取选中的金额
  double getTotalPrice(BusinessCondition businessCondition) {
    var total = 0.0;
    for (PurchaseCondition purchaseCondition in businessCondition.purchaseConditions) {
      for (ProductOption productOption in purchaseCondition.productOptions) {
        if (_checkMap[productOption] ?? false) {
          total += productOption.coinAmount * getQuantityProductOption(productOption);
        }
      }
    }
    return total;
  }

  int getTotalQuantity(BusinessCondition businessCondition) {
    var total = 0;
    for (PurchaseCondition purchaseCondition in businessCondition.purchaseConditions) {
      for (ProductOption productOption in purchaseCondition.productOptions) {
        if (_checkMap[productOption] ?? false) {
          total += getQuantityProductOption(productOption);
        }
      }
    }
    return total;
  }

  String get errorMessage => _errorMessage;

  List<BusinessApply> get list => _list;

  Future<ViewState> businessApply(
      BusinessLevel businessLevel, BusinessCondition businessCondition) async {
    viewState = ViewState.busy;
    try {
      // 筛选出选中的商品
      var list = [];
      for (PurchaseCondition purchaseCondition in businessCondition.purchaseConditions) {
        var item = {};
        var referStoreId = 0;
        for (ProductOption productOption in purchaseCondition.productOptions) {
          if (_checkMap[productOption] ?? false) {
            item['${productOption.id}'] = getQuantityProductOption(productOption);
            referStoreId = productOption.referStoreId;
          }
        }
        list.add({
          'conditionName': purchaseCondition.conditionName,
          'conditionCode': purchaseCondition.conditionCode,
          'productCountMap': item,
          'referStoreId': referStoreId,
          'storeId': purchaseCondition.storeBusinessInfo.storeId,
        });
      }
      // 店铺
      var params = {
        'businessType': businessLevel.businessType,
        'businessLevel': businessLevel.businessLevel,
        'selectedProducts': list,
        'storeId': businessCondition.curStoreBusinessInfo.storeId,
      };
      // 执行
      _list = await api.businessApply(params);
      viewState = ViewState.success;
    } catch (e) {
      _errorMessage = e is DioError ? e.message : e.toString();
      viewState = ViewState.error;
    }
    return viewState;
  }
}
